# 此接口为主要展示页面，展示用户所有通过审核的任务
from flask import Blueprint, jsonify, request
from models import Task, User, DoTask
from exts import db

bp = Blueprint('content', __name__, url_prefix="/content")

@bp.route("/get_content", methods=["POST", "GET"])
def get_content():
    """
    参数要求：

    条件: 任务审核为1, 默认状态也能请求成功,
          一次请求10个数据, 任务创建时间排序降序,
          带参数page: 1开始

    1、任务标题
    2、任务类型
    3、任务介绍
    4、头像链接
    5、用户昵称
    6、用户背景介绍
    """
    # paginate()：分页查询，返回一个分页对象, 参数1：当前是第几页；参数2：每页显示几条记录；参数3：是否要返回错误。
    params = request.get_json() # {'page': 2, 'search_value': '', 'task_type_id': '0'}
    # print(params)
    page = params["page"]
    task_type_id = int(params["task_type_id"])
    search_value = params["search_value"]

    # total = Task.query.filter_by(audit=1).filter_by(taken=0).count()
    # item_ls = Task.query.filter_by(audit=1).filter_by(taken=0).order_by(Task.createtime.desc()).paginate(page, 10, False).items
    if task_type_id > 0:
        item_ls = Task.query.filter_by(audit=1, typeid=task_type_id, taken=0).filter(
            Task.tasktitle.like("%" + search_value + "%") 
        ).order_by(Task.createtime.desc()).paginate(page, 10, False).items
        total = Task.query.filter_by(audit=1, typeid=task_type_id, taken=0).filter(
            Task.tasktitle.like("%" + search_value + "%") 
        ).count()
    else:
        item_ls = Task.query.filter_by(audit=1, taken=0).filter(
            Task.tasktitle.like("%" + search_value + "%") 
        ).order_by(Task.createtime.desc()).paginate(page, 10, False).items
        total = Task.query.filter_by(audit=1, taken=0).filter(
            Task.tasktitle.like("%" + search_value + "%") 
        ).count()

    data_ls = []
    for item in item_ls:
        data = {
                "id": item.id,
                "title": item.tasktitle,
                "avatar": item.user.username, # 在本系统获取图片的api中，是通过email来获取
                "description": item.tasktype.typename,
                "content": item.taskintro,
                "nickname": item.user.nickname,
                "userintro": item.user.userintro,
                "bounty": item.bounty,
                "enddate": item.enddate
               }
        data_ls.append(data)
    return jsonify({"content_data":data_ls, "total": total}) 

# 用户领取任务的接口
@bp.route("/user_get_task", methods=["POST", "GET"])
def user_get_task():
    params = request.get_json()
    # params = {'id': 19, 'email': '123@qq.com', 'username': '406973249', 'isLogin': True}
    if params["isLogin"]:
        tasks = Task.query.filter_by(id=params["id"]).all()
        if len(tasks) == 1:
            task = tasks[0]
            userM = User.query.filter_by(username=params["username"]).first()
            # 全部验证完毕，创建数据
            if userM.email == params["email"]:
                if task.userid == userM.id:
                    return jsonify({
                        "status": 4003,
                        "msg": "自己不能领取自己发布的任务"
                        })

                do_task = DoTask(
                    worker_id = userM.id,
                    task_id = task.id,
                    task_res = 0,
                )
                db.session.add(do_task)
                task.taken = 1
                db.session.commit()
                return "领取任务成功"
            else:
                return "没有这个用户", 403
        else:
           return "没有这个任务", 403 
    else:
        return "错误请求", 403

# 更新用户基本信息
@bp.route("/update_baseinfo", methods=["POST", "GET"])
def update_baseinfo():
    params = request.get_json() # {'email': '143@qq.com', 'username': '616010445', 'isLogin': True}
    if not params["isLogin"]:
        return "不是登录", 400
    
    isUser = User.query.filter(User.email == params["email"]).first()
    if isUser is None:
        return "没有用户",400
    if isUser.username != params["username"]:
        return "参数错误", 400
    baseUserInfo = {
                "nickname": isUser.nickname,
                "email": isUser.email,
                "gender": isUser.gender,
                "userintro": isUser.userintro,
                "username": isUser.username,
                "money": isUser.money
                }
    return jsonify(baseUserInfo)